<?php
namespace Framework\Cache;

/**
 * 缓存的使用
 * $cache->get($key); //取得缓存
 * $cache->set($key); //设置缓存
 * $cache->add($key); //设置缓存 (如果键名不存在的情况下)
 * $cache->exists($key);//返回一个值，指明某个键是否存在于缓存中
 * $cache->delete($key);//通过一个键，删除缓存中对应的值
 * $cache->flush($key);//删除缓存中的所有数据
 */
class Cache
{

	private $store;

	public function __construct($config=[])
	{
		// unset($config['driver']);
		// \Framework\App::configure($this, $config);
	}

	private function driver($driverName=null){
		$predefined = [
			'file'  => FileStore::class,
			'redis' => RedisStore::class,
		];
		$customize = app()->config->get('cache.driver', []);

		$all = array_merge($predefined, $customize);

		if( $driverName !== null ){
			return isset($all[$driverName]) ? $all[$driverName] : null;
		}

		return $all;
	}

	//设置驱动库
	public function store($storeName){
		$this->store = $storeName;
		return $this;
	}

	private function getStore(){
		/**
		 * 如果指定了储存库，则使用指定的储存库，未指定则使用配置的储存库
		 * 指定方式例 $cache->store('redis')->get('article_id');
		 */
        $cacheStoreName = ($this->store === null) ? app()->config->get('cache.default') : $this->store ;
        if( !$cacheStoreName || ctype_space($cacheStoreName) ){
        	throw new \Exception("未配置或指定当前要使用的储存库");
        }

        /**
         * 从配置文件读取储存库配置
         */
        $cacheStore = app()->config->get('cache.store.'.$cacheStoreName);
        if( !is_array($cacheStore) || !isset($cacheStore['driver']) ){
            throw new \Exception("缓存配置错误:{$cacheStoreName}, 未设置对应的储存库");
        }

        //实例化缓存类
        $cacheStoreClassName = $this->driver($cacheStore['driver']);
        if( class_exists($cacheStoreClassName) ){
	        $cache = new $cacheStoreClassName($cacheStore);
	        return $cache;
        }else{
        	throw new \Exception("当前储存库 {$cacheStoreName} 的驱动类 {$cacheStoreClassName} 不存在");
        }
	}


	public function __call(string $function_name, $args)
	{
		// return $this->getStore()->set('nui', '1955');
		return call_user_func_array([$this->getStore(), $function_name], $args);
	}
}